package org.luosl.webmagicx.monitor

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContextExecutor}

class AkkaHttpServer(host:String, port:Int, routes:Seq[Route], name:String) {

  /** akka http */
  implicit val system:ActorSystem = ActorSystem(name)
  implicit val materializer:ActorMaterializer = ActorMaterializer()
  implicit val executionContext:ExecutionContextExecutor = system.dispatcher
  /** 路由 */
  val route:Route = routes.reduce((r1,r2)=> r1 ~ r2)

  def shutdown(): Unit ={
    materializer.shutdown()
    system.terminate()
  }

  def start(): Unit = Await.result(Http().bindAndHandle(route, host, port), 20.second)

}

object AkkaHttpServer {
  def apply(host: String, port: Int, routes:Seq[Route], name:String): AkkaHttpServer = new AkkaHttpServer(host, port, routes,name)
}



